package com.amao.config;

import com.amao.mappers.UsersMapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import com.amao.entity.Users;

/**
 * @package : com.amao.config
 * @Author : yongqi
 * @DATE : 2021/4/25 17:35
 * @描述 ：
 */
@Slf4j
@Component
public class MaoUserDetailsService implements UserDetailsService {

    @Autowired
    PasswordEncoder passwordEncoder;

    @Autowired
    UsersMapper mapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Users users = mapper.selectOne(Wrappers.lambdaQuery(Users.class).eq(Users::getUsername, username));
        if(users != null){
            // TODO 定义角色表 用于绑定用户
            return new User(
                    username,passwordEncoder.encode(users.getPassword()), AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_USER")
            );
        }
        throw new UsernameNotFoundException("无对应用户");
    }
}
